import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:app_settings/app_settings.dart';
import 'package:talk/pages/add/x_add_router.dart';

import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../src/utils/device_utils.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../device/ScanPage.dart';
import '../my/setting_router.dart';

class AddPage extends StatefulWidget {
  final String? scanResult; // 新增：接收扫描结果

  const AddPage({Key? key, this.scanResult}) : super(key: key);

  @override
  State<AddPage> createState() => _AddPageState();
}

class _AddPageState extends State<AddPage> with SingleTickerProviderStateMixin {
  final TextEditingController _codeController = TextEditingController();
  late AnimationController _controller;
  late Animation<double> _animation;
  int _isSao = 0; // 0-显示雷达扫描，1-显示设备列表
  bool _isWiFiEnabled = false; // 标记 Wi-Fi 是否开启
  String _scanData = "";

  @override
  void initState() {
    super.initState();

    // 检查是否有扫描结果传入
    // if (widget.scanResult != null) {
    //   setState(() {
    //     _scanData = widget.scanResult!;
    //     _codeController.text = _scanData;
    //     _isSao = 1; // 自动切换到设备列表页
    //   });
    // }


    // 初始化雷达扫描动画
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    )..repeat();

    _animation = Tween<double>(begin: 0, end: 2 * 3.1415926).animate(
      CurvedAnimation(parent: _controller, curve: Curves.linear),
    );

    // 初始化时检测 Wi-Fi 状态
    _checkWiFiStatus();
  }


  Future<void> _scan() async {
    if (Device.isMobile) {
      NavigatorUtils.unfocus();
      await Future.delayed(const Duration(milliseconds: 500));
      if (!mounted) return;

      // 使用 MaterialPageRoute 确保正确接收返回值
      final result = await Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const ScanPage()),
      );


    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('当前平台暂不支持扫描功能')),
      );
    }
  }
  // Future<void> _scan() async {
  //   if (Device.isMobile) {
  //     NavigatorUtils.unfocus();
  //     await Future.delayed(const Duration(milliseconds: 500));
  //     if (!mounted) return;
  //
  //     // 使用 MaterialPageRoute 确保正确接收返回值
  //     final result = await Navigator.push(
  //       context,
  //       MaterialPageRoute(builder: (context) => const ScanPage()),
  //     );
  //
  //     if (mounted && result != null) {
  //       setState(() {
  //         _scanData = result.toString();
  //         _codeController.text = _scanData;
  //         _isSao = 1; // 扫描成功后切换到设备列表
  //       });
  //       print('扫描成功，结果: $_scanData');
  //     } else {
  //       print('扫描失败或取消');
  //     }
  //   } else {
  //     ScaffoldMessenger.of(context).showSnackBar(
  //       const SnackBar(content: Text('当前平台暂不支持扫描功能')),
  //     );
  //   }
  // }


  // 检测设备 Wi-Fi 状态
  Future<void> _checkWiFiStatus() async {
    final ConnectivityResult result = await Connectivity().checkConnectivity();
    setState(() {
      _isWiFiEnabled = result == ConnectivityResult.wifi;
    });
  }

  // 跳转系统 Wi-Fi 设置（Android/iOS 适配）
  void _openWiFiSettings() async {
    if (Theme.of(context).platform == TargetPlatform.android) {
      await AppSettings.openAppSettings(type: AppSettingsType.wifi);
    } else if (Theme.of(context).platform == TargetPlatform.iOS) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请前往「设置 > Wi-Fi」手动开启'),
          duration: Duration(seconds: 3),
        ),
      );
    }
  }



  @override
  void dispose() {
    _controller.dispose();
    _codeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_tianjiashebei2'),
        backgroundColor: Colors.white,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
        // showSecondRightButton: true,
        // secondRightButtonType: RightButtonType.image,
        // secondRightButtonImgOffset: 10.0,
        // secondRightButtonImgSize: 24.0,
        // secondRightButtonImg: 'images/images/add/s1.png',
        // secondRightButtonImgVerticalOffset: -2.0,
        // onSecondRightButtonPressed: _scan, // 直接调用扫描方法
      ),
      body: Column(
        children: [
          const SizedBox(height: 10),

          // 配网状态提示
          Center(
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 10),
              color: Colors.white,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  const SizedBox(width: 30),
                  Image.asset("images/images/add/s2.png", width: 20),
                  const SizedBox(width: 10),
                  RichText(
                    text: TextSpan(
                      style: const TextStyle(
                        color: Colors.black,
                        fontSize: 13,
                        height: 1.4,
                      ),
                      children: [
                        TextSpan(text: AppLocale.text('d_tianjiashechuyu')),
                        TextSpan(
                          text: AppLocale.text('d_peiwangzhuangtai'),
                          style: const TextStyle(color: Color(0xFF007AFF)),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              NavigatorUtils.push(context, '/user-agreement');
                            },
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),



          // 根据 _isSao 显示不同内容
          _buildMainContent(),

          // 分割线
          Divider(
            height: 20,
            thickness: 1,
            indent: 20,
            endIndent: 20,
            color: Colors.black12,
          ),

          // 手动添加标题
          Padding(
            padding: EdgeInsets.only(top: 20, bottom: 10),
            child: Text(
              AppLocale.text('d_shoudongtianjia'),
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),

          // 设备按钮区域（两行，每行两个按钮）
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                // 第一行：智能摄像机 + 智能门铃
                Row(
                  children: [
                    _buildDeviceButton(
                      context,
                      iconPath: 'images/images/add/q1.png',
                      title: AppLocale.text('d_zhinnegshexinagji'),
                      route: '${XAddRouter.addHandPage}?deviceType=1',
                    ),
                    const SizedBox(width: 20),
                    _buildDeviceButton(
                      context,
                      iconPath: 'images/images/add/q2.png',
                      title: AppLocale.text('d_zhinengmenling'),
                      route: '${XAddRouter.addHandPage}?deviceType=2',
                    ),
                  ],
                ),

                const SizedBox(height: 20),

                // 第二行：智能门禁机 + 智能室内机
                Row(
                  children: [
                    _buildDeviceButton(
                      context,
                      iconPath: 'images/images/add/q3.png',
                      title: AppLocale.text('d_zhinengmenjinji'),
                      route: '${XAddRouter.addHandPage}?deviceType=3',
                    ),
                    const SizedBox(width: 20),
                    _buildDeviceButton(
                      context,
                      iconPath: 'images/images/add/q4.png',
                      title: AppLocale.text('d_zhinengshineiji'),
                      route: '${XAddRouter.addHandPage}?deviceType=4',
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 根据 _isSao 构建主内容
  Widget _buildMainContent() {
    if (_isSao == 0) {
      return _buildRadarScan();
    } else {
      return _buildDeviceList();
    }
  }

  // 构建雷达扫描界面（含 Wi-Fi 提示容器）
  Widget _buildRadarScan() {
    return Column(
      children: [
        const SizedBox(height: 10),

        // Wi-Fi 提示容器：未开启时显示，可点击跳转设置
        if (!_isWiFiEnabled)
          GestureDetector(
            onTap: _openWiFiSettings,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              margin: const EdgeInsets.symmetric(horizontal: 30),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.grey.shade300, width: 1),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '打开 Wi-Fi',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        Text(
                          '搜索设备需开启 Wi-Fi',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey.shade600,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: 32,
                    height: 32,
                    decoration: BoxDecoration(
                      color: Colors.grey.shade200,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: const Icon(
                      Icons.warning_amber_rounded,
                      color: Colors.red,
                      size: 18,
                    ),
                  ),
                ],
              ),
            ),
          ),

        const SizedBox(height: 5),



        // 雷达扫描动画容器
        Container(
          padding: const EdgeInsets.symmetric(vertical: 30),
          alignment: Alignment.center,
          child: Container(
            width: 200,
            height: 200,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.grey.withOpacity(0.3), width: 1),
            ),
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 雷达背景（白色未扫描部分）
                Container(
                  width: 200,
                  height: 200,
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.white,
                  ),
                ),

                // 雷达扫描扇区（蓝色渐变）
                AnimatedBuilder(
                  animation: _animation,
                  builder: (context, child) {
                    return Transform.rotate(
                      angle: _animation.value,
                      child: CustomPaint(
                        painter: RadarPainter(),
                        size: const Size(200, 200),
                      ),
                    );
                  },
                ),

                // 雷达同心圆背景
                Container(
                  width: 200,
                  height: 200,
                  child: CustomPaint(
                    painter: RadarBackgroundPainter(),
                  ),
                ),

                // 中心圆点
                const CircleAvatar(
                  radius: 6,
                  backgroundColor: Color(0xFF007AFF),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 构建设备列表界面
  Widget _buildDeviceList() {
    return Container(
      child: Column(
        children: [
          const SizedBox(height: 20),


          const SizedBox(height: 20),

          // 按钮区域，每行两个按钮
          Wrap(
            spacing: 20, // 水平间距
            runSpacing: 20, // 垂直间距
            alignment: WrapAlignment.center,
            children: [
              _buildDeviceButton2(
                iconPath: 'images/images/add/q1.png',
                title: AppLocale.text('d_zhinnegshexinagji'),
                route: '/smart-camera',
              ),
              _buildDeviceButton2(
                iconPath: 'images/images/add/q2.png',
                title: AppLocale.text('d_zhinengmenling'),
                route: '/smart-doorbell',
              ),
              _buildDeviceButton2(
                iconPath: 'images/images/add/q3.png',
                title: AppLocale.text('d_zhinengmenjinji'),
                route: '/smart-access-control',
              ),
              _buildDeviceButton2(
                iconPath: 'images/images/add/q4.png',
                title: AppLocale.text('d_zhinengshineiji'),
                route: '/smart-indoor-unit',
              ),
            ],
          ),

          const SizedBox(height: 210)
        ],
      ),
    );
  }

  // 构建可跳转的设备按钮（带图标和文字）
  Widget _buildDeviceButton2({
    required String iconPath,
    required String title,
    required String route,
  }) {
    return GestureDetector(
      onTap: (){
        // NavigatorUtils.push(context, route);
        print("sdfsfad");
        // print(_scanData);
      },
      child: Column(
        children: [
          Image.asset(
            iconPath,
            width: 40,
            height: 40,
          ),
          const SizedBox(height: 8),
          Text(
            title,
            style: const TextStyle(
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  // 构建占满一行的设备按钮（带图标和文字）
  Widget _buildDeviceButton(
      BuildContext context, {
        required String iconPath,
        required String title,
        required String route,
      }) {
    return Expanded(
      child: GestureDetector(
        onTap: () => NavigatorUtils.push(context, route),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 10),
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            children: [
              Image.asset(
                iconPath,
                width: 35,
                height: 35,
              ),
              const SizedBox(width: 10),
              Text(
                title,
                style: const TextStyle(
                  fontSize: 14,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 雷达扫描扇形画笔
class RadarPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2;

    final gradient = SweepGradient(
      startAngle: -3.1415926 / 2,
      endAngle: -3.1415926 / 2 + 3.1415926 / 2,
      colors: [
        const Color(0xFF007AFF).withOpacity(0.9),
        const Color(0xFF007AFF).withRed(1),
      ],
      stops: const [0.0, 1.0],
    );

    final Paint paint = Paint()
      ..shader = gradient.createShader(
        Rect.fromCircle(center: center, radius: radius),
      )
      ..style = PaintingStyle.fill;

    final Path path = Path();
    path.moveTo(center.dx, center.dy);
    path.arcTo(
      Rect.fromCircle(center: center, radius: radius),
      -3.1415926 / 2,
      3.1415926 / 2,
      false,
    );
    path.close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

// 雷达同心圆背景画笔
class RadarBackgroundPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final Paint paint = Paint()
      ..color = Colors.grey.withOpacity(0.2)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;

    // 绘制同心圆
    canvas.drawCircle(
      Offset(size.width / 2, size.height / 2),
      size.width / 2,
      paint,
    );
    canvas.drawCircle(
      Offset(size.width / 2, size.height / 2),
      size.width / 3,
      paint,
    );
    canvas.drawCircle(
      Offset(size.width / 2, size.height / 2),
      size.width / 6,
      paint,
    );

    // 绘制十字线
    paint.color = Colors.grey.withOpacity(0.15);
    canvas.drawLine(
      Offset(0, size.height / 2),
      Offset(size.width, size.height / 2),
      paint,
    );
    canvas.drawLine(
      Offset(size.width / 2, 0),
      Offset(size.width / 2, size.height),
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}